<template>
  <div class="retry-mistake-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">错题重做</h1>
      <div class="header-actions">
        <el-button @click="refreshRetryList">
          <el-icon><Refresh /></el-icon>
          刷新列表
        </el-button>
        <el-button @click="viewRetryHistory">
          <el-icon><History /></el-icon>
          重做历史
        </el-button>
      </div>
    </div>

    <!-- 错题分类和筛选 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <el-select v-model="categoryFilter" placeholder="选择知识点分类" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
          
          <el-select v-model="sourceFilter" placeholder="选择来源" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="模拟考试" value="mock" />
            <el-option label="知识点练习" value="practice" />
            <el-option label="专项训练" value="special" />
            <el-option label="其他" value="other" />
          </el-select>
          
          <el-select v-model="difficultyFilter" placeholder="选择难度" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
          
          <el-select v-model="retryStatusFilter" placeholder="选择重做状态" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="未重做" value="pending" />
            <el-option label="已重做(正确)" value="correct" />
            <el-option label="已重做(错误)" value="incorrect" />
          </el-select>
          
          <el-button type="primary" @click="applyFilters">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 错题统计 -->
    <div class="stats-section">
      <div class="stats-grid">
        <el-card class="stat-card total-mistakes">
          <div class="stat-icon">📝</div>
          <div class="stat-info">
            <div class="stat-value">{{ totalMistakes }}</div>
            <div class="stat-label">总错题数</div>
          </div>
        </el-card>
        
        <el-card class="stat-card pending-mistakes">
          <div class="stat-icon">⏳</div>
          <div class="stat-info">
            <div class="stat-value">{{ pendingMistakes }}</div>
            <div class="stat-label">待重做</div>
          </div>
        </el-card>
        
        <el-card class="stat-card correct-mistakes">
          <div class="stat-icon">✅</div>
          <div class="stat-info">
            <div class="stat-value">{{ correctMistakes }}</div>
            <div class="stat-label">重做正确</div>
          </div>
        </el-card>
        
        <el-card class="stat-card mastery-rate">
          <div class="stat-icon">🎯</div>
          <div class="stat-info">
            <div class="stat-value">{{ overallMasteryRate }}%</div>
            <div class="stat-label">总体掌握率</div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 错题列表 -->
    <div class="mistakes-list-section">
      <el-card class="mistakes-card">
        <div class="mistakes-header">
          <h2>错题列表</h2>
          <div class="mistakes-stats">
            <span>共 {{ filteredMistakes.length }} 道错题</span>
            <span v-if="isFiltered" class="filtered-text">（已筛选）</span>
          </div>
        </div>
        
        <!-- 批量操作 -->
        <div class="batch-actions">
          <el-button @click="selectAllMistakes">
            <el-icon><Check /></el-icon>
            全选
          </el-button>
          <el-button @click="clearSelection">
            <el-icon><Delete /></el-icon>
            取消选择
          </el-button>
          <el-button type="primary" @click="startBatchRetry" :disabled="selectedMistakes.length === 0">
            <el-icon><Play /></el-icon>
            批量重做 ({{ selectedMistakes.length }})
          </el-button>
          <el-button danger @click="removeSelectedMistakes" :disabled="selectedMistakes.length === 0">
            <el-icon><Delete /></el-icon>
            移除所选错题
          </el-button>
        </div>
        
        <div class="mistakes-content">
          <div v-if="filteredMistakes.length === 0" class="no-mistakes">
            <el-empty description="暂无错题" />
            <div class="no-mistakes-text">恭喜您，当前筛选条件下没有错题！</div>
          </div>
          
          <el-table
            v-else
            v-loading="isLoading"
            :data="paginatedMistakes"
            style="width: 100%"
            border
            row-key="id"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            
            <el-table-column prop="id" label="ID" width="80" align="center">
              <template #default="scope">
                {{ scope.row.id }}
              </template>
            </el-table-column>
            
            <el-table-column prop="stem" label="题目" min-width="400">
              <template #default="scope">
                <div class="question-stem-preview">{{ scope.row.stem }}</div>
              </template>
            </el-table-column>
            
            <el-table-column prop="categoryName" label="知识点" width="150" align="center">
              <template #default="scope">
                <el-tag>{{ scope.row.categoryName }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="source" label="来源" width="120" align="center">
              <template #default="scope">
                <el-tag :type="getSourceType(scope.row.source)">{{ getSourceName(scope.row.source) }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="difficulty" label="难度" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getDifficultyType(scope.row.difficulty)">{{ getDifficultyName(scope.row.difficulty) }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="addedDate" label="添加时间" width="160" align="center">
              <template #default="scope">
                {{ formatDate(scope.row.addedDate) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="retryStatus" label="重做状态" width="120" align="center">
              <template #default="scope">
                <el-tag :type="getRetryStatusType(scope.row.retryStatus)">{{ getRetryStatusName(scope.row.retryStatus) }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="retryCount" label="重做次数" width="100" align="center" />
            
            <el-table-column label="操作" width="180" align="center" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="retrySingleMistake(scope.row.id)"
                  :disabled="scope.row.retryStatus === 'correct'"
                >
                  <el-icon><Play /></el-icon>
                  重做
                </el-button>
                <el-button
                  size="small"
                  @click="viewMistakeDetails(scope.row.id)"
                >
                  <el-icon><Reading /></el-icon>
                  查看
                </el-button>
                <el-button
                  size="small"
                  danger
                  @click="removeMistake(scope.row.id)"
                >
                  <el-icon><Delete /></el-icon>
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div v-if="filteredMistakes.length > 0" class="mistakes-pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredMistakes.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 重做对话框 -->
    <el-dialog
      v-model="retryDialogVisible"
      title="错题重做"
      width="900px"
      :fullscreen="isFullscreen"
      :before-close="handleRetryDialogClose"
    >
      <!-- 重做进度 -->
      <div class="retry-progress">
        <el-progress
          :percentage="(currentRetryIndex + 1) / retryQuestions.length * 100"
          :format="formatRetryProgress"
        />
        <div class="retry-progress-info">
          <span>{{ currentRetryIndex + 1 }}/{{ retryQuestions.length }} 题</span>
          <span v-if="retryTimer > 0">用时: {{ formatTime(retryTimer) }}</span>
        </div>
      </div>
      
      <!-- 题目内容 -->
      <div v-if="currentRetryQuestion" class="retry-question-content">
        <div class="retry-question-header">
          <span class="retry-question-type">{{ getQuestionTypeName(currentRetryQuestion.type) }}</span>
          <span class="retry-question-difficulty" :class="`difficulty-${currentRetryQuestion.difficulty}`">
            {{ getDifficultyName(currentRetryQuestion.difficulty) }}
          </span>
        </div>
        
        <div class="retry-question-stem">
          <h3>{{ currentRetryQuestion.stem }}</h3>
          <div v-if="currentRetryQuestion.imageUrl" class="retry-question-image">
            <img :src="currentRetryQuestion.imageUrl" :alt="currentRetryQuestion.stem" />
          </div>
        </div>
        
        <!-- 选项 -->
        <div v-if="currentRetryQuestion.options" class="retry-question-options">
          <div
            v-for="(option, index) in currentRetryQuestion.options"
            :key="index"
            :class="['retry-option-item', { 'selected': retrySelectedOptions.includes(index), 'disabled': isRetryAnswered }]"
            @click="selectRetryOption(index)"
          >
            <div class="retry-option-label">{{ getOptionLabel(index) }}</div>
            <div class="retry-option-content">{{ option }}</div>
          </div>
        </div>
        
        <!-- 填空/简答 -->
        <div v-else-if="currentRetryQuestion.type === 'blank' || currentRetryQuestion.type === 'essay'" class="retry-question-answer-input">
          <el-input
            v-model="retryTextAnswer"
            :type="currentRetryQuestion.type === 'essay' ? 'textarea' : 'text'"
            placeholder="请输入答案"
            :autosize="currentRetryQuestion.type === 'essay' ? { minRows: 4, maxRows: 8 } : false"
            :disabled="isRetryAnswered"
          />
        </div>
        
        <!-- 答案和解析 -->
        <div v-if="showRetryAnswer" class="retry-answer-explanation">
          <div class="retry-user-answer">
            <h4>您的答案:</h4>
            <p>{{ getRetryUserAnswerDisplay() }}</p>
          </div>
          
          <div class="retry-correct-answer">
            <h4>正确答案:</h4>
            <p>{{ getRetryCorrectAnswerDisplay() }}</p>
          </div>
          
          <div class="retry-explanation">
            <h4>解析:</h4>
            <p>{{ currentRetryQuestion.explanation }}</p>
          </div>
        </div>
      </div>
      
      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="retry-dialog-footer">
          <el-button @click="toggleRetryFullscreen">
            <el-icon>{{ isFullscreen ? 'MinusSquare' : 'PlusSquare' }}</el-icon>
            {{ isFullscreen ? '退出全屏' : '全屏' }}
          </el-button>
          <el-button @click="handleRetryDialogClose">取消</el-button>
          <div class="retry-navigation-buttons">
            <el-button
              @click="prevRetryQuestion"
              :disabled="currentRetryIndex === 0 || isRetryAnswered"
            >
              <el-icon><ArrowLeft /></el-icon>
              上一题
            </el-button>
            <el-button
              v-if="!isRetryAnswered"
              type="primary"
              @click="submitRetryAnswer"
              :loading="isRetrySubmitting"
            >
              提交答案
            </el-button>
            <el-button
              v-else
              type="primary"
              @click="nextRetryQuestion"
              :disabled="currentRetryIndex === retryQuestions.length - 1"
            >
              下一题
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </span>
      </template>
    </el-dialog>

    <!-- 错题详情对话框 -->
    <el-dialog
      v-model="mistakeDetailDialogVisible"
      title="错题详情"
      width="800px"
    >
      <div v-if="selectedMistakeDetail" class="mistake-detail-content">
        <div class="mistake-detail-header">
          <span class="mistake-detail-id">ID: {{ selectedMistakeDetail.id }}</span>
          <span class="mistake-detail-source">{{ getSourceName(selectedMistakeDetail.source) }}</span>
        </div>
        
        <div class="mistake-detail-question">
          <h3>{{ selectedMistakeDetail.stem }}</h3>
          <div v-if="selectedMistakeDetail.imageUrl" class="mistake-detail-image">
            <img :src="selectedMistakeDetail.imageUrl" :alt="selectedMistakeDetail.stem" />
          </div>
        </div>
        
        <div v-if="selectedMistakeDetail.options" class="mistake-detail-options">
          <div
            v-for="(option, index) in selectedMistakeDetail.options"
            :key="index"
            class="mistake-detail-option"
            :class="{
              'correct': Array.isArray(selectedMistakeDetail.correctAnswers) && 
                         selectedMistakeDetail.correctAnswers.every(item => typeof item === 'number') &&
                         (selectedMistakeDetail.correctAnswers as number[]).includes(index),
              'user-selected': selectedMistakeDetail.userAnswers.includes(index)
            }"
          >
            <div class="mistake-detail-option-label">{{ getOptionLabel(index) }}</div>
            <div class="mistake-detail-option-content">{{ option }}</div>
            <div v-if="Array.isArray(selectedMistakeDetail.correctAnswers) && 
                       selectedMistakeDetail.correctAnswers.every(item => typeof item === 'number') &&
                       (selectedMistakeDetail.correctAnswers as number[]).includes(index)" class="mistake-detail-correct-mark">
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
        
        <div v-else-if="selectedMistakeDetail.type === 'blank' || selectedMistakeDetail.type === 'essay'" class="mistake-detail-answer-display">
          <div class="mistake-detail-user-answer">
            <h4>您的答案:</h4>
            <p>{{ selectedMistakeDetail.userAnswers[0] || '未作答' }}</p>
          </div>
          
          <div class="mistake-detail-correct-answer">
            <h4>正确答案:</h4>
            <p>{{ selectedMistakeDetail.correctAnswers[0] }}</p>
          </div>
        </div>
        
        <div class="mistake-detail-explanation">
          <h4>解析:</h4>
          <p>{{ selectedMistakeDetail.explanation }}</p>
        </div>
        
        <div class="mistake-detail-meta">
          <div class="mistake-detail-meta-item">
            <span class="meta-label">知识点:</span>
            <span class="meta-value">{{ selectedMistakeDetail.categoryName }}</span>
          </div>
          <div class="mistake-detail-meta-item">
            <span class="meta-label">难度:</span>
            <span class="meta-value">{{ getDifficultyName(selectedMistakeDetail.difficulty) }}</span>
          </div>
          <div class="mistake-detail-meta-item">
            <span class="meta-label">添加时间:</span>
            <span class="meta-value">{{ formatDate(selectedMistakeDetail.addedDate) }}</span>
          </div>
          <div class="mistake-detail-meta-item">
            <span class="meta-label">重做状态:</span>
            <span class="meta-value">{{ getRetryStatusName(selectedMistakeDetail.retryStatus) }}</span>
          </div>
          <div class="mistake-detail-meta-item">
            <span class="meta-label">重做次数:</span>
            <span class="meta-value">{{ selectedMistakeDetail.retryCount }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="mistake-detail-footer">
          <el-button @click="mistakeDetailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="selectedMistakeDetail?.id && retrySingleMistake(selectedMistakeDetail.id)">
            <el-icon><Play /></el-icon>
            立即重做
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Refresh,
    Search,
    Check,
    Delete,
    Reading,
    ArrowLeft,
    ArrowRight
  } from '@element-plus/icons-vue'

// 响应式数据
const isLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const categoryFilter = ref('all')
const sourceFilter = ref('all')
const difficultyFilter = ref('all')
const retryStatusFilter = ref('all')
const isFiltered = ref(false)
const selectedMistakes = ref<string[]>([])
const retryDialogVisible = ref(false)
const mistakeDetailDialogVisible = ref(false)
const isFullscreen = ref(false)
const currentRetryIndex = ref(0)
const retrySelectedOptions = ref<number[]>([])
const retryTextAnswer = ref('')
const isRetryAnswered = ref(false)
const isRetrySubmitting = ref(false)
const showRetryAnswer = ref(false)
const retryTimer = ref(0)
const timerInterval = ref<number | null>(null)

// 分类数据
const categories = ref([
  { id: '1', name: '图形推理' },
  { id: '2', name: '定义判断' },
  { id: '3', name: '类比推理' },
  { id: '4', name: '逻辑判断' },
  { id: '5', name: '言语理解' },
  { id: '6', name: '数量关系' },
  { id: '7', name: '资料分析' }
])

// 错题接口
interface Mistake {
  id: string
  stem: string
  type: 'single' | 'multiple' | 'blank' | 'essay'
  difficulty: 'easy' | 'medium' | 'hard'
  options?: string[]
  correctAnswers: number[] | string[]
  userAnswers: any[]
  explanation: string
  categoryId: string
  categoryName: string
  source: 'mock' | 'practice' | 'special' | 'other'
  addedDate: Date
  retryStatus: 'pending' | 'correct' | 'incorrect'
  retryCount: number
  lastRetryDate?: Date
  imageUrl?: string
  knowledgePoints: string[]
}

// 模拟错题数据
const mistakes = ref<Mistake[]>([
  {
    id: 'm1',
    stem: '从所给的四个选项中，选择最合适的一个填入问号处，使之呈现一定的规律性：\n图形：○ △ □ ○ △ ?',
    type: 'single',
    difficulty: 'easy',
    options: ['○', '△', '□', '◇'],
    correctAnswers: [2],
    userAnswers: [0],
    explanation: '观察图形序列，发现是以○ △ □为周期循环出现的，所以△后面应该是□，正确答案为C选项。',
    categoryId: '1',
    categoryName: '图形推理',
    source: 'mock',
    addedDate: new Date('2024-05-20T10:00:00'),
    retryStatus: 'pending',
    retryCount: 0,
    knowledgePoints: ['图形推理', '周期性规律']
  },
  {
    id: 'm2',
    stem: '下列不属于哺乳动物特征的是：',
    type: 'single',
    difficulty: 'medium',
    options: ['胎生', '哺乳', '体温恒定', '用鳃呼吸'],
    correctAnswers: [3],
    userAnswers: [2],
    explanation: '哺乳动物的主要特征包括胎生、哺乳、体温恒定等，而用鳃呼吸是鱼类的特征，所以正确答案为D选项。',
    categoryId: '2',
    categoryName: '定义判断',
    source: 'practice',
    addedDate: new Date('2024-05-18T09:15:00'),
    retryStatus: 'correct',
    retryCount: 1,
    lastRetryDate: new Date('2024-05-22T14:30:00'),
    knowledgePoints: ['生物学', '动物分类']
  },
  {
    id: 'm3',
    stem: '下列哪些属于清洁能源？（多选）',
    type: 'multiple',
    difficulty: 'medium',
    options: ['太阳能', '风能', '水能', '煤炭', '天然气'],
    correctAnswers: [0, 1, 2],
    userAnswers: [0, 1, 4],
    explanation: '清洁能源是指不排放污染物、能够直接用于生产生活的能源，包括太阳能、风能、水能、生物能等。煤炭和天然气属于化石能源，燃烧会产生污染物，所以正确答案为A、B、C选项。',
    categoryId: '3',
    categoryName: '类比推理',
    source: 'special',
    addedDate: new Date('2024-05-15T11:30:00'),
    retryStatus: 'incorrect',
    retryCount: 2,
    lastRetryDate: new Date('2024-05-23T09:45:00'),
    knowledgePoints: ['环境保护', '能源分类']
  },
  {
    id: 'm4',
    stem: '中国的首都是_________。',
    type: 'blank',
    difficulty: 'easy',
    correctAnswers: ['北京'],
    userAnswers: ['上海'],
    explanation: '北京是中华人民共和国的首都，是全国的政治中心、文化中心和国际交往中心。',
    categoryId: '4',
    categoryName: '逻辑判断',
    source: 'mock',
    addedDate: new Date('2024-05-10T08:45:00'),
    retryStatus: 'pending',
    retryCount: 0,
    knowledgePoints: ['地理', '中国国情']
  },
  {
    id: 'm5',
    stem: '简述影响气候的主要因素。',
    type: 'essay',
    difficulty: 'hard',
    correctAnswers: ['纬度位置、海陆位置、地形地势、洋流、人类活动等'],
    userAnswers: ['温度和湿度'],
    explanation: '影响气候的主要因素包括：\n1. 纬度位置：决定了太阳高度角和昼夜长短的变化，是影响气候的基本因素。\n2. 海陆位置：海洋和陆地的热力性质差异导致了沿海和内陆气候的不同。\n3. 地形地势：山脉对气流的阻挡作用、海拔高度的变化都会影响气候。\n4. 洋流：暖流增温增湿，寒流降温减湿。\n5. 人类活动：如温室气体排放、城市化等也会对气候产生影响。',
    categoryId: '5',
    categoryName: '言语理解',
    source: 'practice',
    addedDate: new Date('2024-05-05T14:00:00'),
    retryStatus: 'pending',
    retryCount: 0,
    knowledgePoints: ['地理', '气候学']
  },
  {
    id: 'm6',
    stem: '计算：1 + 2 + 3 + ... + 100 = ?',
    type: 'blank',
    difficulty: 'medium',
    correctAnswers: ['5050'],
    userAnswers: ['5500'],
    explanation: '这是一个等差数列求和问题，首项a1=1，末项an=100，项数n=100，根据等差数列求和公式S=n(a1+an)/2，可得S=100×(1+100)/2=5050。',
    categoryId: '6',
    categoryName: '数量关系',
    source: 'special',
    addedDate: new Date('2024-05-01T10:30:00'),
    retryStatus: 'correct',
    retryCount: 1,
    lastRetryDate: new Date('2024-05-21T16:20:00'),
    knowledgePoints: ['数学', '等差数列']
  },
  {
    id: 'm7',
    stem: '根据以下数据，计算2023年的同比增长率：\n2022年GDP：100万亿元\n2023年GDP：110万亿元',
    type: 'blank',
    difficulty: 'medium',
    correctAnswers: ['10%'],
    userAnswers: ['11%'],
    explanation: '同比增长率=(本期数-同期数)/同期数×100%，代入数据可得(110-100)/100×100%=10%。',
    categoryId: '7',
    categoryName: '资料分析',
    source: 'mock',
    addedDate: new Date('2024-04-28T15:15:00'),
    retryStatus: 'incorrect',
    retryCount: 1,
    lastRetryDate: new Date('2024-05-20T11:05:00'),
    knowledgePoints: ['资料分析', '增长率计算']
  }
])

// 重做题目列表
const retryQuestions = ref<Mistake[]>([])
const selectedMistakeDetail = ref<Mistake | null>(null)

// 计算属性
const filteredMistakes = computed(() => {
  let filtered = [...mistakes.value]
  
  // 根据分类筛选
  if (categoryFilter.value !== 'all') {
    filtered = filtered.filter(mistake => mistake.categoryId === categoryFilter.value)
  }
  
  // 根据来源筛选
  if (sourceFilter.value !== 'all') {
    filtered = filtered.filter(mistake => mistake.source === sourceFilter.value)
  }
  
  // 根据难度筛选
  if (difficultyFilter.value !== 'all') {
    filtered = filtered.filter(mistake => mistake.difficulty === difficultyFilter.value)
  }
  
  // 根据重做状态筛选
  if (retryStatusFilter.value !== 'all') {
    filtered = filtered.filter(mistake => mistake.retryStatus === retryStatusFilter.value)
  }
  
  // 按添加时间倒序排列
  filtered.sort((a, b) => b.addedDate.getTime() - a.addedDate.getTime())
  
  return filtered
})

// 分页后的错题列表
const paginatedMistakes = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredMistakes.value.slice(startIndex, endIndex)
})

// 统计数据
const totalMistakes = computed(() => mistakes.value.length)
const pendingMistakes = computed(() => mistakes.value.filter(m => m.retryStatus === 'pending').length)
const correctMistakes = computed(() => mistakes.value.filter(m => m.retryStatus === 'correct').length)
const overallMasteryRate = computed(() => {
  const total = mistakes.value.length
  if (total === 0) return 0
  return Math.round((correctMistakes.value / total) * 100)
})

// 当前重做题目
const currentRetryQuestion = computed(() => {
  return retryQuestions.value[currentRetryIndex.value] || null
})

// 方法
const formatDate = (date: Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

const getQuestionTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    blank: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

const getDifficultyName = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return difficultyMap[difficulty] || difficulty
}

const getDifficultyType = (difficulty: string) => {
  const typeMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || 'info'
}

const getSourceName = (source: string) => {
  const sourceMap: Record<string, string> = {
    mock: '模拟考试',
    practice: '知识点练习',
    special: '专项训练',
    other: '其他'
  }
  return sourceMap[source] || source
}

const getSourceType = (source: string) => {
  const typeMap: Record<string, string> = {
    mock: 'primary',
    practice: 'success',
    special: 'warning',
    other: 'info'
  }
  return typeMap[source] || 'info'
}

const getRetryStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '未重做',
    correct: '已重做(正确)',
    incorrect: '已重做(错误)'
  }
  return statusMap[status] || status
}

const getRetryStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'info',
    correct: 'success',
    incorrect: 'danger'
  }
  return typeMap[status] || 'info'
}

const getOptionLabel = (index: number) => {
  return String.fromCharCode(65 + index)
}

const formatRetryProgress = () => {
  return ''
}

const getRetryCorrectAnswerDisplay = () => {
  if (!currentRetryQuestion.value) return ''
  
  if (currentRetryQuestion.value.type === 'blank' || currentRetryQuestion.value.type === 'essay') {
    return currentRetryQuestion.value.correctAnswers.join('、')
  } else if (currentRetryQuestion.value.options) {
    return currentRetryQuestion.value.correctAnswers
      .map(answer => {
        if (typeof answer === 'number') {
          return getOptionLabel(answer) + '.' + currentRetryQuestion.value.options![answer]
        }
        return answer
      })
      .join('，')
  }
  return ''
}

const getRetryUserAnswerDisplay = () => {
  if (!currentRetryQuestion.value) return ''
  
  if (currentRetryQuestion.value.type === 'blank' || currentRetryQuestion.value.type === 'essay') {
    return retryTextAnswer.value || '未作答'
  } else if (currentRetryQuestion.value.options) {
    if (retrySelectedOptions.value.length === 0) {
      return '未作答'
    }
    return retrySelectedOptions.value
      .map((answer: number) => getOptionLabel(answer) + '.' + currentRetryQuestion.value.options![answer])
      .join('，')
  }
  return ''
}

// 表格选择处理
const handleSelectionChange = (selection: Array<any>) => {
  selectedMistakes.value = selection.map(item => (item as Mistake).id)
}

// 全选
const selectAllMistakes = () => {
  // 在实际应用中，这里应该调用表格的toggleAllSelection方法
  ElMessage.info('全选功能待实现')
}

// 清除选择
const clearSelection = () => {
  selectedMistakes.value = []
}

// 应用筛选
const applyFilters = () => {
  isFiltered.value = categoryFilter.value !== 'all' ||
    sourceFilter.value !== 'all' ||
    difficultyFilter.value !== 'all' ||
    retryStatusFilter.value !== 'all'
  currentPage.value = 1
}

// 刷新列表
const refreshRetryList = () => {
  isLoading.value = true
  // 模拟刷新操作
  setTimeout(() => {
    isLoading.value = false
    ElMessage.success('错题列表已刷新')
  }, 500)
}

// 查看重做历史
const viewRetryHistory = () => {
  ElMessage.info('查看重做历史功能待实现')
}

// 单个错题重做
const retrySingleMistake = (id: string) => {
  const mistake = mistakes.value.find(m => m.id === id)
  if (mistake) {
    retryQuestions.value = [mistake]
    startRetrySession()
  }
}

// 批量重做
const startBatchRetry = () => {
  if (selectedMistakes.value.length === 0) {
    ElMessage.warning('请先选择要重做的错题')
    return
  }
  
  retryQuestions.value = mistakes.value.filter(m => selectedMistakes.value.includes(m.id))
  startRetrySession()
}

// 开始重做会话
const startRetrySession = () => {
  currentRetryIndex.value = 0
  retrySelectedOptions.value = []
  retryTextAnswer.value = ''
  isRetryAnswered.value = false
  isRetrySubmitting.value = false
  showRetryAnswer.value = false
  retryTimer.value = 0
  retryDialogVisible.value = true
  
  // 开始计时
  startTimer()
}

// 开始计时
const startTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
  }
  
  timerInterval.value = window.setInterval(() => {
    retryTimer.value++
  }, 1000)
}

// 停止计时
const stopTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
    timerInterval.value = null
  }
}

// 选择重做选项
const selectRetryOption = (index: number) => {
  if (isRetryAnswered.value) return
  
  const question = currentRetryQuestion.value
  if (!question) return
  
  if (question.type === 'single') {
    // 单选题只能选择一个选项
    retrySelectedOptions.value = [index]
  } else if (question.type === 'multiple') {
    // 多选题可以选择多个选项
    const optionIndex = retrySelectedOptions.value.indexOf(index)
    if (optionIndex > -1) {
      retrySelectedOptions.value.splice(optionIndex, 1)
    } else {
      retrySelectedOptions.value.push(index)
    }
  }
}

// 提交重做答案
const submitRetryAnswer = () => {
  const question = currentRetryQuestion.value
  if (!question || isRetryAnswered.value) return
  
  isRetrySubmitting.value = true
  
  // 模拟提交答案的延迟
  setTimeout(() => {
    let isCorrect = false
    
    if (question.type === 'single' || question.type === 'multiple') {
      // 比较选项答案
      isCorrect = retrySelectedOptions.value.length === question.correctAnswers.length &&
        retrySelectedOptions.value.every(option => {
          // 类型守卫，确保在运行时处理correctAnswers的联合类型
          if (Array.isArray(question.correctAnswers)) {
            // 检查是否所有元素都是数字
            const allNumbers = question.correctAnswers.every(item => typeof item === 'number');
            if (allNumbers) {
              return (question.correctAnswers as number[]).includes(option);
            }
          }
          return false;
        })
    } else if (question.type === 'blank' || question.type === 'essay') {
      // 简单的文本答案比较
      isCorrect = question.correctAnswers.some(answer => 
        retryTextAnswer.value.toLowerCase().includes((answer as string).toLowerCase())
      )
    }
    
    // 更新错题状态
    const mistakeIndex = mistakes.value.findIndex(m => m.id === question.id)
    if (mistakeIndex > -1) {
      mistakes.value[mistakeIndex] = {
        ...mistakes.value[mistakeIndex],
        retryStatus: isCorrect ? 'correct' : 'incorrect',
        retryCount: mistakes.value[mistakeIndex].retryCount + 1,
        lastRetryDate: new Date()
      }
    }
    
    isRetryAnswered.value = true
    showRetryAnswer.value = true
    isRetrySubmitting.value = false
  }, 500)
}

// 上一题
const prevRetryQuestion = () => {
  if (currentRetryIndex.value > 0) {
    currentRetryIndex.value--
    resetRetryQuestionState()
  }
}

// 下一题
const nextRetryQuestion = () => {
  if (currentRetryIndex.value < retryQuestions.value.length - 1) {
    currentRetryIndex.value++
    resetRetryQuestionState()
  } else {
    // 最后一题，结束重做会话
    endRetrySession()
  }
}

// 重置重做题目状态
const resetRetryQuestionState = () => {
  retrySelectedOptions.value = []
  retryTextAnswer.value = ''
  isRetryAnswered.value = false
  showRetryAnswer.value = false
}

// 结束重做会话
const endRetrySession = () => {
  // 停止计时
  stopTimer()
  
  // 统计重做结果
  const correctCount = retryQuestions.value.filter(q => {
    const mistake = mistakes.value.find(m => m.id === q.id)
    return mistake && mistake.retryStatus === 'correct'
  }).length
  
  const totalCount = retryQuestions.value.length
  const accuracy = totalCount > 0 ? Math.round((correctCount / totalCount) * 100) : 0
  
  ElMessage.success(`重做完成！正确率：${accuracy}% (${correctCount}/${totalCount})`)
  
  // 关闭对话框
  retryDialogVisible.value = false
}

// 切换全屏
const toggleRetryFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

// 处理重做对话框关闭
const handleRetryDialogClose = () => {
  if (retryTimer.value > 0) {
    ElMessageBox.confirm(
      '确定要放弃当前重做吗？',
      '确认放弃',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续重做',
        type: 'warning'
      }
    ).then(() => {
      stopTimer()
      retryDialogVisible.value = false
    }).catch(() => {
      // 用户选择继续重做
    })
  } else {
    retryDialogVisible.value = false
  }
}

// 查看错题详情
const viewMistakeDetails = (id: string) => {
  const mistake = mistakes.value.find(m => m.id === id)
  if (mistake) {
    selectedMistakeDetail.value = mistake
    mistakeDetailDialogVisible.value = true
  }
}

// 移除单个错题
const removeMistake = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要移除这道错题吗？移除后将无法恢复。',
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = mistakes.value.findIndex(m => m.id === id)
    if (index > -1) {
      mistakes.value.splice(index, 1)
    }
    
    // 如果当前页没有数据了，返回上一页
    if (paginatedMistakes.value.length === 0 && currentPage.value > 1) {
      currentPage.value -= 1
    }
    
    ElMessage.success('错题已移除')
  } catch (error) {
    // 用户取消操作
  }
}

// 移除选中的错题
const removeSelectedMistakes = async () => {
  if (selectedMistakes.value.length === 0) {
    ElMessage.warning('请先选择要移除的错题')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要移除选中的 ${selectedMistakes.value.length} 道错题吗？移除后将无法恢复。`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 移除选中的错题
    mistakes.value = mistakes.value.filter(m => !selectedMistakes.value.includes(m.id))
    
    // 清除选择
    selectedMistakes.value = []
    
    // 如果当前页没有数据了，返回上一页
    if (paginatedMistakes.value.length === 0 && currentPage.value > 1) {
      currentPage.value -= 1
    }
    
    ElMessage.success(`已成功移除 ${selectedMistakes.value.length} 道错题`)
  } catch (error) {
    // 用户取消操作
  }
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current
}

// 组件挂载时初始化
onMounted(() => {
  // 可以在这里加载用户的错题数据
})

// 组件卸载时清理
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
  }
})
</script>

<style lang="scss" scoped>
.retry-mistake-view {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-card {
  border-radius: 12px;
  overflow: hidden;
}

.filter-content {
  display: flex;
  gap: 15px;
  align-items: center;
  padding: 20px;
  flex-wrap: wrap;
}

.filter-select {
  width: 200px;
}

.stats-section {
  margin-bottom: 30px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 25px;
  border-radius: 12px;
  transition: all 0.3s ease;
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.total-mistakes {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.pending-mistakes {
  background-color: #fdf6ec;
  border-color: #e6a23c;
}

.correct-mistakes {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.mastery-rate {
  background-color: #fef0f0;
  border-color: #f56c6c;
}

.stat-icon {
  font-size: 48px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.mistakes-list-section {
  margin-bottom: 30px;
}

.mistakes-card {
  border-radius: 12px;
  overflow: hidden;
}

.mistakes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  flex-wrap: wrap;
  gap: 15px;
}

.mistakes-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.mistakes-stats {
  font-size: 14px;
  color: #6b7280;
}

.filtered-text {
  color: #409eff;
}

.batch-actions {
  display: flex;
  gap: 10px;
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e7eb;
  flex-wrap: wrap;
}

.mistakes-content {
  padding: 20px;
}

.no-mistakes {
  text-align: center;
  padding: 60px 20px;
}

.no-mistakes-text {
  margin-top: 20px;
  font-size: 16px;
  color: #6b7280;
}

.question-stem-preview {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.mistakes-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  border-top: 1px solid #e5e7eb;
}

/* 重做对话框样式 */
.retry-progress {
  margin-bottom: 20px;
}

.retry-progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
  color: #6b7280;
}

.retry-question-content {
  padding: 10px 0;
}

.retry-question-header {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.retry-question-type {
  font-size: 14px;
  color: #6b7280;
  background-color: #f5f7fa;
  padding: 5px 12px;
  border-radius: 16px;
}

.retry-question-difficulty {
  font-size: 14px;
  padding: 5px 12px;
  border-radius: 16px;
}

.retry-question-stem {
  margin-bottom: 30px;
}

.retry-question-stem h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.6;
  margin: 0 0 15px 0;
}

.retry-question-image {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.retry-question-image img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.retry-question-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.retry-option-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 15px 20px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
  &.selected {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
  &.disabled {
    cursor: not-allowed;
    opacity: 0.8;
  }
}

.retry-option-label {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  min-width: 24px;
  text-align: center;
}

.retry-option-content {
  font-size: 16px;
  color: #4b5563;
  line-height: 1.6;
}

.retry-question-answer-input {
  margin-bottom: 30px;
}

.retry-answer-explanation {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 10px;
}

.retry-user-answer,
.retry-correct-answer,
.retry-explanation {
  margin-bottom: 20px;
}

.retry-user-answer:last-child,
.retry-correct-answer:last-child,
.retry-explanation:last-child {
  margin-bottom: 0;
}

.retry-user-answer h4,
.retry-correct-answer h4,
.retry-explanation h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 10px 0;
}

.retry-user-answer p,
.retry-correct-answer p,
.retry-explanation p {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.6;
  margin: 0;
}

.retry-dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.retry-navigation-buttons {
  display: flex;
  gap: 15px;
}

/* 错题详情对话框样式 */
.mistake-detail-content {
  padding: 10px 0;
}

.mistake-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

.mistake-detail-id {
  font-size: 14px;
  color: #6b7280;
}

.mistake-detail-source {
  font-size: 14px;
  color: #409eff;
}

.mistake-detail-question {
  margin-bottom: 30px;
}

.mistake-detail-question h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.6;
  margin: 0 0 15px 0;
}

.mistake-detail-image {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.mistake-detail-image img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.mistake-detail-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.mistake-detail-option {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 15px 20px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  position: relative;
}

.mistake-detail-option.correct {
  border-color: #67c23a;
  background-color: #f0f9eb;
}

.mistake-detail-option.user-selected {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.mistake-detail-option-label {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  min-width: 24px;
  text-align: center;
}

.mistake-detail-option-content {
  font-size: 16px;
  color: #4b5563;
  line-height: 1.6;
  flex: 1;
}

.mistake-detail-correct-mark {
  color: #67c23a;
  font-size: 20px;
}

.mistake-detail-answer-display {
  margin-bottom: 30px;
}

.mistake-detail-user-answer,
.mistake-detail-correct-answer {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 8px;
}

.mistake-detail-user-answer {
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
}

.mistake-detail-correct-answer {
  background-color: #f0f9eb;
  border: 1px solid #67c23a;
}

.mistake-detail-user-answer h4,
.mistake-detail-correct-answer h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 10px 0;
}

.mistake-detail-user-answer p,
.mistake-detail-correct-answer p {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.6;
  margin: 0;
}

.mistake-detail-explanation {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 30px;
}

.mistake-detail-explanation h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 10px 0;
}

.mistake-detail-explanation p {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.6;
  margin: 0;
}

.mistake-detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.mistake-detail-meta-item {
  display: flex;
  gap: 10px;
  align-items: center;
  flex: 1;
  min-width: 200px;
}

.meta-label {
  font-size: 14px;
  color: #6b7280;
  min-width: 80px;
}

.meta-value {
  font-size: 14px;
  color: #1f2937;
  font-weight: 500;
}

.mistake-detail-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-select {
    width: 100%;
  }
}

@media (max-width: 992px) {
  .batch-actions {
    flex-direction: column;
  }
  
  .retry-dialog-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .retry-navigation-buttons {
    justify-content: center;
  }
  
  .mistake-detail-meta {
    flex-direction: column;
    align-items: stretch;
  }
  
  .mistake-detail-meta-item {
    min-width: auto;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .retry-question-header,
  .mistake-detail-header {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .retry-question-stem h3,
  .mistake-detail-question h3 {
    font-size: 16px;
  }
}
</style>